package com.thread.prodcustrom;

public class TestWaitNotifyConsumerAndProducer {

	/*当前生成数量*/
	static int currentNum = 0;
	/*最大生成数量*/
	static int MAX_NUM = 10;
	/*最小消费数量*/
	static int MIN_NUM = 0;
	/*wait和notify控制对象*/
	private static final String lock = "lock";

	public static void main(String args[]) {
		//创建一个生产者
		new Thread(new Producer()).start();

		//创建两个消费者
		new Thread(new Consumer()).start();
		new Thread(new Consumer()).start();
	}


	static class Producer implements Runnable {
		public void product() {
			while (true) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				synchronized (lock) {
					currentNum++;
					System.out.println("Producer now product num:" + currentNum);
					lock.notifyAll();

					if (currentNum == MAX_NUM) {
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}

			}
		}

		@Override
		public void run() {
			product();
		}
	}

	static class Consumer implements Runnable {
		public void consume() {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (lock) {
					if (currentNum == MIN_NUM) {
						lock.notifyAll();
						continue;
					}
					System.out.println(new StringBuilder(Thread.currentThread().getName())
							.append(" Consumer now consumption num:").append(currentNum));
					currentNum--;
				}
			}
		}

		@Override
		public void run() {
			consume();
		}
	}
}
